//
//  SXHWebViewController.m
//  dsBridge
//
//  Created by sxh on 2020/9/15.
//

#import "SXHWebViewController.h"
#import "TipsHud.h"
#import "BaseTools.h"
#import "BaseFunction.h"
#import "httpService.h"
#import "photos.h"
#import "macro.h"
#import "SXHFileManager.h"
#import "SXHDownloader.h"
#import "SSZipArchive.h"
#import "SXHBaseWebView.h"

@interface SXHWebViewController ()
<
    WKNavigationDelegate
>
@property (nonatomic , strong) WKWebViewConfiguration *configuration;

@end

@implementation SXHWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.edgesForExtendedLayout = UIRectEdgeNone;

    if (!_params) {
        _params = @{}.mutableCopy;
    }
    
    _configuration = [[WKWebViewConfiguration alloc] init];
//    [_configuration setValue:@(YES) forKey:@"_allowUniversalAccessFromFileURLs"];
//    NSString *sessionId = [[NSUserDefaults standardUserDefaults] objectForKey:@"sessionId"];
//    NSString *cookie = [NSString stringWithFormat:@"document.cookie=\'JSESSIONID=%@;path=/\'",sessionId];
//    WKUserScript *script = [[WKUserScript alloc] initWithSource:cookie
//                                                  injectionTime:WKUserScriptInjectionTimeAtDocumentStart
//                                               forMainFrameOnly:NO];
//
//    [_configuration.userContentController addUserScript:script];
    
    [self initView];
    
    //防止在web页面加载完成后，没有收到通知关闭加载指示器。 延时10秒关闭指示器
    //创建并行队列
    dispatch_queue_t gcd = dispatch_queue_create("sd", DISPATCH_QUEUE_CONCURRENT);
    dispatch_time_t timer = dispatch_time(DISPATCH_TIME_NOW, 10 * NSEC_PER_SEC);
    dispatch_after(timer, gcd, ^{
        
        dispatch_async(dispatch_get_main_queue(), ^{

            [[TipsHud sharedInstance] hideTips];
        });

    });
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:[_ishiddenNavigate boolValue] animated:animated];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
//    [self.navigationController setNavigationBarHidden:![_ishiddenNavigate boolValue] animated:animated];
}

//初始化dweb页面
- (void)initView {
    
    self.view.backgroundColor = [UIColor whiteColor];
    
}

#pragma mark - WKNavigationDelegate

- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    [[TipsHud sharedInstance] showLoadingOnView:self.view];
    //后续注入cookie
    NSString *sessionId = [[NSUserDefaults standardUserDefaults] objectForKey:@"sessionId"];
    NSString *cookie = [NSString stringWithFormat:@"document.cookie=\'JSESSIONID=%@;path=/\'",sessionId];
    [webView evaluateJavaScript:cookie completionHandler:^(id _Nullable result, NSError * _Nullable error) {

    }];
}
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation {
    
    [[TipsHud sharedInstance] hideTips];
}

// 页面导航失败
- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    
    [[TipsHud sharedInstance] hideTips];
}

// 页面加载失败
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    
    [[TipsHud sharedInstance] hideTips];
}

#pragma mark - event methods
/// 清除wkwebview缓存
- (void)deleteWebCache {
    NSSet *websiteDataTypes = [WKWebsiteDataStore allWebsiteDataTypes];

    NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];

    [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{
        
    }];
    
    NSString *libraryDir = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,
    NSUserDomainMask, YES)[0];
    NSString *bundleId  =  [[[NSBundle mainBundle] infoDictionary]
    objectForKey:@"CFBundleIdentifier"];
    NSString *webkitFolderInLib = [NSString stringWithFormat:@"%@/WebKit",libraryDir];
    NSString *webKitFolderInCaches = [NSString
    stringWithFormat:@"%@/Caches/%@/WebKit",libraryDir,bundleId];
     NSString *webKitFolderInCachesfs = [NSString
     stringWithFormat:@"%@/Caches/%@/fsCachedData",libraryDir,bundleId];

    NSError *error;
    /* iOS8.0 WebView Cache的存放路径 */
    [[NSFileManager defaultManager] removeItemAtPath:webKitFolderInCaches error:&error];
    [[NSFileManager defaultManager] removeItemAtPath:webkitFolderInLib error:nil];

    /* iOS7.0 WebView Cache的存放路径 */
    [[NSFileManager defaultManager] removeItemAtPath:webKitFolderInCachesfs error:&error];
}

#pragma mark -- getters && setters

- (SXHBaseWebView *)webview {
    if (!_webview) {
        
        _webview = [[SXHBaseWebView alloc] initWithFrame:self.view.bounds configuration:self.configuration];
        _webview.navigationDelegate = self;
        [self.view addSubview:_webview];
    }
    return _webview;
}

- (void)setUrl:(NSString *)url {
    _url = url;
    [self.webview loadingUrl:url];
}

- (void)setParams:(NSMutableDictionary *)params {
    _params = params;
    self.webview.params = params;
}

- (void)setIshiddenNavigate:(NSString *)ishiddenNavigate {
    _ishiddenNavigate = ishiddenNavigate;
    
    [self.navigationController setNavigationBarHidden: [ishiddenNavigate boolValue] animated:YES];
}

@end
